package com.grep.extra.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.grep.extra.factory.data.IDataQueue;
import com.grep.extra.factory.handle.IHandler;

public class ThreadWorker<K,T> extends Thread {

	static Logger logger = LoggerFactory.getLogger(ThreadWorker.class);    
	
	private IHandler<K,T> handler ;
	
	ThreadPool<K,T> pool ;

	private ThreadWorker(){}
	
	public ThreadWorker(IHandler<K,T> handler,ThreadPool<K,T> pool){
		this.handler = handler;
		this.pool = pool;
	}
	
	public void init() {
		
	}

	@Override
	public void run() {
		logger.info("[ThreadPool] start a thread :thread id =>"+Thread.currentThread().getId()+
				",task thread count =>" + pool.getThreadCount() + ".") ;
	
		IDataQueue<K> task = handler.getTask() ;
		while(true){
			//根据任务数量判断是否需要处理线程结束
			if(pool.reduceThread(task.size())){
				break ;
			}
			//业务处理
			K k = task.take() ;
			if(k != null){
				handler.process(k) ;
			}
			//根据任务数量判断并增加处理线程
			pool.addThread(handler,task.size());
		}
	}
	
}
